package chat

import (
	"fmt"
	"hft/Http/Services/chat"
	"hft/Http/Services/chat/chat_model"
	utils "hft/Http/Utils"
	"hft/tools"
	"hft/tools/upload"
	"path/filepath"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Chat struct{}

func (*Chat) LeaveChat(c *gin.Context) {
	var data *chat_model.ChatSearchWithPort
	c.ShouldBindJSON(&data)
	token := c.Request.Header.Get("user-token")
	sid, _ := strconv.Atoi(c.Request.Header.Get("sid"))
	ip := c.ClientIP()
	if err := chat.ChatService.LeaveChat(&data.ChatSearch, token, ip, data.Port, sid); err != nil {
		utils.FailWithMessage(err.Error(), c)
	} else {
		utils.Ok(c)
	}
}

func (*Chat) UploadFile(c *gin.Context) {
	file, _ := c.FormFile("file")
	ext := filepath.Ext(file.Filename)
	if ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != ".gif" {
		utils.FailWithMessage("只允许上传图片文件", c)
		return
	}
	if file.Size > 2*1024*1024 {
		utils.FailWithMessage("文件不可超过2MB", c)
		return
	}
	if filepath, _, err := upload.OssAliyun.UploadFile(file, fmt.Sprintf("%v.%v", tools.GenUUID(), ext)); err != nil {
		fmt.Println(err)
		utils.FailWithMessage(err.Error(), c)
	} else {
		utils.OkWithData(gin.H{"url": filepath}, c)
	}
}

var ChatController = new(Chat)
